package com.example.votsnfcphone;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

public class MainActivity extends Activity implements OnClickListener {

	ImageView mButtonSi;
	ImageView mButtonNo;
	TextView mTextViewNomConsulta;
	TextView mTextViewNFCtagid;
	ImageView mImageViewConsultaImage;
	AsyncTask<String, Void, JSONObject> asynct;
	String nfctagid;
	int consultaid;
	int deviceid;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.votlayout);

		getActionBar().setTitle(null);
		
		mButtonSi = (ImageView) findViewById(R.id.si);
		mButtonNo = (ImageView) findViewById(R.id.no);
		mImageViewConsultaImage = (ImageView) findViewById(R.id.consultaimg);
		mButtonSi.setOnClickListener(this);
		mButtonNo.setOnClickListener(this);
		mTextViewNomConsulta = (TextView) findViewById(R.id.nomconsulta);
		mTextViewNFCtagid = (TextView) findViewById(R.id.nfctagid);

		ImageView acostaiv = (ImageView) findViewById(R.id.acosta);
		
		resolveIntent(getIntent());
		
		String action = getIntent().getAction();
		if (!NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
			mButtonSi.setVisibility(View.INVISIBLE);
			mButtonNo.setVisibility(View.INVISIBLE);
			mImageViewConsultaImage.setVisibility(View.INVISIBLE);
			acostaiv.setVisibility(View.VISIBLE);
			mTextViewNomConsulta.setText("Apropa el smartphone a un punt de vot");
		} else {
			mImageViewConsultaImage.setVisibility(View.VISIBLE);
			mButtonSi.setVisibility(View.VISIBLE);
			mButtonNo.setVisibility(View.VISIBLE);
			acostaiv.setVisibility(View.INVISIBLE);
		}
		
		String android_id = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
		deviceid = hex2decimal(android_id);
	}
	
	public static int hex2decimal(String s) {
        String digits = "0123456789ABCDEF";
        s = s.toUpperCase();
        int val = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int d = digits.indexOf(c);
            val = 16*val + d;
        }
        return val;
    }

	@Override
	public void onDestroy() {
		if (asynct != null)
			asynct.cancel(true);
		super.onDestroy();
	}

	private class DownloadJson extends AsyncTask<String, Void, JSONObject> {
		protected JSONObject doInBackground(String... urls) {
	    	JSONObject jsonconsulta = null;
			try {
				JSONObject jsonconsultabynfc = new JSONObject(downloadString(urls[0]));
				consultaid = jsonconsultabynfc.getInt("consultaid");
				String url2 = data.infoconsultaurl + "?consulta=" + jsonconsultabynfc.getInt("consultaid");
		    	jsonconsulta = new JSONObject(downloadString(url2));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	         return jsonconsulta;
	     }

		protected void onPostExecute(JSONObject result) {
			try {
				mTextViewNomConsulta.setText(result.getString("nom"));
				Log.e("url",data.baseurl + result.getString("logo_consulta_pano"));
				UrlImageViewHelper.setUrlDrawable(mImageViewConsultaImage, data.baseurl + result.getString("logo_consulta_pano"), R.drawable.loading, null);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NullPointerException e) {
				
			}
		}
	}
	
	private class Votar extends AsyncTask<String, Void, JSONObject> {
		protected JSONObject doInBackground(String... urls) {
	    	JSONObject jsonvot = null;
			try {
				jsonvot = new JSONObject(downloadString(urls[0]));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	         return jsonvot;
	     }

		protected void onPostExecute(JSONObject result) {
			try {
				if (result.getString("response_status").equals("0"));
				Toast.makeText(getApplicationContext(), "Vot enviat correctament", Toast.LENGTH_LONG).show();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public String downloadString(String url) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(MainActivity.class.toString(), "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.activity_main, menu);
//		return true;
//	}

	@Override
	public void onNewIntent(Intent intent) {
		setIntent(intent);
		resolveIntent(intent);
	}

	private String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("0x");
		if (src == null || src.length <= 0) {
			return null;
		}

		char[] buffer = new char[2];
		for (int i = 0; i < src.length; i++) {
			buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
			buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
			System.out.println(buffer);
			stringBuilder.append(buffer);
		}

		return stringBuilder.toString();
	}

	void resolveIntent(Intent intent) {
		String action = intent.getAction();
		if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
			byte[] tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
			String scannedTag = bytesToHexString(tagId);
			mTextViewNFCtagid.setText(scannedTag);
			asynct = new DownloadJson().execute(data.consultabytagidurl
					+ "?nfctagid=" + scannedTag);
			nfctagid = scannedTag;
			
			Log.e("ID tag", scannedTag);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.si:
			new Votar().execute(data.votarurl + "?vot=1&consulta=" + consultaid + "&dispositiu=" + deviceid + "&nfctagid=" + nfctagid);
			mButtonNo.setBackgroundResource(R.drawable.no);
			mButtonSi.setBackgroundResource(R.drawable.si_marked);
			break;
		case R.id.no:
			new Votar().execute(data.votarurl + "?vot=0&consulta=" + consultaid + "&dispositiu=" + deviceid + "&nfctagid=" + nfctagid);
			mButtonNo.setBackgroundResource(R.drawable.no_marked);
			mButtonSi.setBackgroundResource(R.drawable.si);
			break;

		default:
			break;
		}
		
	}
}
